/* Copyright 2009 Sony Mathew, Minneapolis MN. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */
package com.xsm.gwt.widgets.client;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Models a map between Objects and its labels.
 * 
 * @author Sony Mathew
 */
public class LabelModel<T> {
    
    private final Collection<T> objs;
    private final LabelProvider<T> labelProvider;
    private final Map<String, T> labelMap = new HashMap<String, T>();
    
    /**
     * Provide labels for the objects.
     */
    public interface LabelProvider<T> {        
        public String getLabel(T t);
    }
    
    /**
     * Provide a collection of objects and a LabelProvider.
     *  
     * author Sony Mathew
     */
    public LabelModel(Collection<T> objs, LabelProvider<T> labelProvider) {
        this.objs = new ArrayList<T>(objs);
        this.labelProvider = labelProvider;
        for (T o : objs) {
            labelMap.put(labelProvider.getLabel(o), o);
        }
    }
    
    public Collection<String> getLabels() {
        return labelMap.keySet();
    }
    
    public Collection<T> getObjects() {
        return Collections.unmodifiableCollection(objs);
    }
    
    public T getObject(String label) {
        return labelMap.get(label);
    }
    
    public String getLabel(T o) {
        return labelProvider.getLabel(o);
    }    
}
